package com.yuexunit.mobilenurse.module.Transportation.ui;

import android.app.PendingIntent;
import android.content.DialogInterface;
import android.content.Intent;
import android.content.IntentFilter;
import android.nfc.NfcAdapter;
import android.nfc.Tag;
import android.nfc.tech.MifareUltralight;
import android.util.Log;
import android.view.View;
import android.widget.BaseAdapter;
import android.widget.Button;
import android.widget.ImageView;
import android.widget.LinearLayout;
import android.widget.TextView;
import android.widget.Toast;

import com.alibaba.fastjson.JSON;
import com.yuexunit.mobilenurse.R;
import com.yuexunit.mobilenurse.config.AppConfig;
import com.yuexunit.mobilenurse.module.Transportation.adapter.TransportationRecordAdapter;
import com.yuexunit.mobilenurse.module.Transportation.bean.OperNotice_OpsList;
import com.yuexunit.mobilenurse.module.Transportation.bean.RfidBean;
import com.yuexunit.mobilenurse.module.Transportation.bean.TransportationRecord_Opsinfo;
import com.yuexunit.mobilenurse.module.Transportation.bean.YXTransportationExec;
import com.yuexunit.mobilenurse.module.Transportation.bean.YXTransportationExecFail;
import com.yuexunit.mobilenurse.module.Transportation.model.impl.OperNoticeModel;
import com.yuexunit.mobilenurse.module.Transportation.model.impl.SelectOperModel;
import com.yuexunit.mobilenurse.module.Transportation.model.impl.TransportationModel;
import com.yuexunit.mobilenurse.module.Transportation.presenter.IOperNoticePresenter;
import com.yuexunit.mobilenurse.module.Transportation.presenter.ISelectOperPresenter;
import com.yuexunit.mobilenurse.module.Transportation.presenter.ITransportationPresenter;
import com.yuexunit.mobilenurse.module.Transportation.presenter.impl.OperNoticePresenter;
import com.yuexunit.mobilenurse.module.Transportation.presenter.impl.SelectOperPresenter;
import com.yuexunit.mobilenurse.module.Transportation.presenter.impl.TransportationPresenter;
import com.yuexunit.mobilenurse.module.Transportation.ui.view.IOperNoticeView;
import com.yuexunit.mobilenurse.module.Transportation.ui.view.ISelectOperView;
import com.yuexunit.mobilenurse.module.Transportation.ui.view.ITransportationView;
import com.yuexunit.mobilenurse.widget.Dialog_Transportation;
import com.yuexunit.mobilenurse.widget.EmptyLayout;
import com.yuexunit.mobilenurse.widget.FixedSwipeListView;
import com.yuexunit.mobilenurse.widget.LoadingDialog;

import org.kymjs.kjframe.KJActivity;
import org.kymjs.kjframe.ui.ViewInject;
import org.kymjs.kjframe.utils.PreferenceHelper;

import java.io.IOException;
import java.util.ArrayList;
import java.util.Arrays;

import butterknife.Bind;
import butterknife.ButterKnife;
import butterknife.OnClick;

/**
 * Created by work-jx on 2016/9/23.
 */
public class Act_Transportation extends KJActivity implements ISelectOperView, ITransportationView ,IOperNoticeView{

    @Bind(R.id.transport_title_01)
    TextView transportTitle01;
    @Bind(R.id.transport_title_01_img)
    ImageView transportTitle01Img;
    @Bind(R.id.transport_title_01_img_01)
    ImageView transportTitle01Img01;
    @Bind(R.id.transport_title_02)
    TextView transportTitle02;
    @Bind(R.id.transport_title_02_img)
    ImageView transportTitle02Img;
    @Bind(R.id.transport_title_02_img_01)
    ImageView transportTitle02Img01;
    @Bind(R.id.transport_sure_btn)
    Button transportSureBtn;
    @Bind(R.id.transport_oper_ll)
    LinearLayout transportOperLl;
    @Bind(R.id.trsportation_list)
    FixedSwipeListView trsportationList;
    @Bind(R.id.empty_layout)
    EmptyLayout emptyLayout;
    @Bind(R.id.transport_record_ll)
    LinearLayout transportRecordLl;
    @Bind(R.id.transportation_visit_name)
    TextView transportationVisitName;
    @Bind(R.id.transportation_visit_bed)
    TextView transportationVisitBed;
    @Bind(R.id.transportation_visit_visitno)
    TextView transportationVisitVisitno;
    @Bind(R.id.transportation_worker_name)
    TextView transportationWorkerName;
    @Bind(R.id.transportation_worker_no)
    TextView transportationWorkerNo;
    @Bind(R.id.transportation_operted_name)
    TextView transportationOpertedName;
    @Bind(R.id.transport_title_03)
    TextView transportTitle03;
    @Bind(R.id.transport_title_03_img)
    ImageView transportTitle03Img;
    @Bind(R.id.transport_title_03_img_01)
    ImageView transportTitle03Img01;
    @Bind(R.id.oper_notice_time)
    TextView operNoticeTime;
    @Bind(R.id.oper_notice_vicitno)
    TextView operNoticeVicitno;
    @Bind(R.id.oper_notice_name)
    TextView operNoticeName;
    @Bind(R.id.oper_notice_bed)
    TextView operNoticeBed;
    @Bind(R.id.oper_notice_diag)
    TextView operNoticeDiag;
    @Bind(R.id.oper_notice_opsname)
    TextView operNoticeOpsname;
    @Bind(R.id.oper_notice_ll)
    LinearLayout operNoticeLl;

    //nfc相关
//    private NfcAdapter mNfcAdapter;
//    private PendingIntent mPendingIntent;
    private IntentFilter[] mFilters;// Intent 过滤器
    private String[][] mTechLists;// technologies 列表

    //病人住院号
    private String Visitno;
    ISelectOperPresenter presenter;
    ITransportationPresenter presenterRfid;
    private BaseAdapter adapter;
    ArrayList<TransportationRecord_Opsinfo> opsinfos = new ArrayList<TransportationRecord_Opsinfo>();
    String rfid;
    LoadingDialog loadDialog;
    Dialog_Transportation.Builder builder_transportation;
    RfidBean rfidBean;
    TransportationRecord_Opsinfo opsinfo = new TransportationRecord_Opsinfo();

    //手术通知
    IOperNoticePresenter presenterNotice;

    @Override
    public void setRootView() {
        setContentView(R.layout.act_transportation);
        ButterKnife.bind(this);
    }

    @Override
    public void initWidget() {
        super.initWidget();
//        //nfc初始化
//        mNfcAdapter = NfcAdapter.getDefaultAdapter(this);
//        if (mNfcAdapter == null) {
//            ViewInject.toast("当前设备不支持NFC");
//            finish();
//            return;
//        }
//        if (!mNfcAdapter.isEnabled()) {
//            ViewInject.toast("请打开NFC");
//            finish();
//            return;
//        }
//
//        mPendingIntent = PendingIntent.getActivity(this, 0, new Intent(this, getClass()).addFlags(Intent.FLAG_ACTIVITY_SINGLE_TOP), 0);
//        IntentFilter ifilters = new IntentFilter();
//        ifilters.addAction(NfcAdapter.ACTION_NDEF_DISCOVERED);
//        ifilters.addAction(NfcAdapter.ACTION_TAG_DISCOVERED);
//        ifilters.addAction(NfcAdapter.ACTION_TECH_DISCOVERED);
//
//        //intent 过滤器，过滤类型为 NDEF_DISCOVERED，TAG_DISCOVERED，TECH_DISCOVERED
//        mFilters = new IntentFilter[] {ifilters,};
//        //存放支持technologies的数组
//        mTechLists = new String[][] {
//                new String[] {
//                        Ndef.class.getName(),
//                        NfcA.class.getName(),
//                        NfcB.class.getName(),
//                        NfcF.class.getName(),
//                        NfcV.class.getName(),
//                        MifareClassic.class.getName()
//                }
//        };
    }

    @Override
    public void initData() {
        super.initData();
        loadDialog = new LoadingDialog(this);
        presenter = new SelectOperPresenter(this, new SelectOperModel());
        presenterRfid = new TransportationPresenter(new TransportationModel(), this);
        presenterNotice = new OperNoticePresenter(new OperNoticeModel(),this);
        Visitno = PreferenceHelper.readString(aty, AppConfig.CURRENT_PATIENT_INFO, AppConfig.CURRENT_PATIENT_VISITNO);
        transportationVisitName.setText("病人姓名:" + PreferenceHelper.readString(aty, AppConfig.CURRENT_PATIENT_INFO, AppConfig.CURRENT_PATIENT_NAME));
        transportationVisitBed.setText("床位号:" + PreferenceHelper.readString(aty, AppConfig.CURRENT_PATIENT_INFO, AppConfig.CURRENT_PATIENT_BEDCODE));
        transportationVisitVisitno.setText("住院号:" + PreferenceHelper.readString(aty, AppConfig.CURRENT_PATIENT_INFO, AppConfig.CURRENT_PATIENT_VISITNO));
    }

    @Override
    public void onResume() {
        super.onResume();
        //设置此activity最先处理nfc intent
//        if (mNfcAdapter != null) {
//            mNfcAdapter.enableForegroundDispatch(this, mPendingIntent, null, null);
//        }
    }

    @Override
    protected void onPause() {
        super.onPause();
//        if (mNfcAdapter != null) {
//            mNfcAdapter.disableForegroundDispatch(this);
//        }
    }


    @OnClick({R.id.back, R.id.transportation_ll, R.id.transport_ll_01, R.id.transport_ll_02, R.id.transport_sure_btn,R.id.transport_ll_03})
    public void onClick(View view) {
        switch (view.getId()) {
            case R.id.back:
                finish();
                break;
            case R.id.transportation_ll:
                Intent intent = new Intent(aty, Act_SelectOper.class);
                startActivityForResult(intent, 1);
                break;
            case R.id.transport_ll_01:
                transportTitle01.setTextColor(getResources().getColor(R.color.doc_advice_01));
                transportTitle01Img.setVisibility(View.VISIBLE);
                transportTitle01Img01.setVisibility(View.GONE);
                transportTitle02.setTextColor(getResources().getColor(R.color.doc_advice_03));
                transportTitle02Img.setVisibility(View.GONE);
                transportTitle02Img01.setVisibility(View.VISIBLE);
                transportTitle03.setTextColor(getResources().getColor(R.color.doc_advice_03));
                transportTitle03Img.setVisibility(View.GONE);
                transportTitle03Img01.setVisibility(View.VISIBLE);

                transportOperLl.setVisibility(View.VISIBLE);
                transportRecordLl.setVisibility(View.GONE);
                operNoticeLl.setVisibility(View.GONE);
                break;
            case R.id.transport_ll_02:
                transportTitle01.setTextColor(getResources().getColor(R.color.doc_advice_03));
                transportTitle01Img.setVisibility(View.GONE);
                transportTitle01Img01.setVisibility(View.VISIBLE);
                transportTitle02.setTextColor(getResources().getColor(R.color.doc_advice_01));
                transportTitle02Img.setVisibility(View.VISIBLE);
                transportTitle02Img01.setVisibility(View.GONE);
                transportTitle03.setTextColor(getResources().getColor(R.color.doc_advice_03));
                transportTitle03Img.setVisibility(View.GONE);
                transportTitle03Img01.setVisibility(View.VISIBLE);

                transportOperLl.setVisibility(View.GONE);
                transportRecordLl.setVisibility(View.VISIBLE);
                operNoticeLl.setVisibility(View.GONE);
                if (opsinfos.size() > 0) {
                    opsinfos.clear();
                    adapter.notifyDataSetChanged();
                }
                emptyLayout.setErrorType(EmptyLayout.NETWORK_LOADING);
                presenter.showOpsList(Visitno);
                break;
            case R.id.transport_sure_btn:
//                showDialog(rfidBean);
                loadDialog.setCanceledOnTouchOutside(false);
                loadDialog.show();
                execOps();
                break;
            case R.id.transport_ll_03:
                transportTitle01.setTextColor(getResources().getColor(R.color.doc_advice_03));
                transportTitle01Img.setVisibility(View.GONE);
                transportTitle01Img01.setVisibility(View.VISIBLE);
                transportTitle02.setTextColor(getResources().getColor(R.color.doc_advice_03));
                transportTitle02Img.setVisibility(View.GONE);
                transportTitle02Img01.setVisibility(View.VISIBLE);
                transportTitle03.setTextColor(getResources().getColor(R.color.doc_advice_01));
                transportTitle03Img.setVisibility(View.VISIBLE);
                transportTitle03Img01.setVisibility(View.GONE);

                transportOperLl.setVisibility(View.GONE);
                transportRecordLl.setVisibility(View.GONE);
                operNoticeLl.setVisibility(View.VISIBLE);

                if(null != opsinfo.getRequestno())
                {
                    presenterNotice.showOpsNoticeList(opsinfo.getRequestno());
                }
                break;
        }
    }

    @Override
    protected void onActivityResult(int requestCode, int resultCode, Intent data) {
        super.onActivityResult(requestCode, resultCode, data);
        switch (resultCode) {
            case RESULT_OK:
                opsinfo = (TransportationRecord_Opsinfo) data.getExtras().getSerializable("opsinfo");
                transportationOpertedName.setText("手术名称:" + opsinfo.getOpsname());
                if (rfidBean != null) {
                    transportSureBtn.setEnabled(true);
                }
                presenterNotice.showOpsNoticeList(opsinfo.getRequestno());
                break;
            default:
                break;
        }
    }

    /*
    NFC识别
     */
    @Override
    public void onNewIntent(Intent intent) {
        super.onNewIntent(intent);
        Tag tag = intent.getParcelableExtra(NfcAdapter.EXTRA_TAG);
        rfid = readTag(tag);
        loadDialog.setCanceledOnTouchOutside(false);
        loadDialog.show();
        presenterRfid.getRfidInfo(rfid);
    }

    public String readTag(Tag tag) {
        String[] techlist = tag.getTechList();
        if (Arrays.toString(techlist).contains("MifareUltralight")) {
            MifareUltralight mifareUltralight = MifareUltralight.get(tag);
            try {
                mifareUltralight.connect();

                byte[] data = mifareUltralight.readPages(4);
//                Log.e("jx", bytesToHexString(data));
//                return bytesToHexString(data);
                return new String(data);

            } catch (Exception e) {
                // TODO: handle exception
                e.printStackTrace();
            } finally {
                try {
                    mifareUltralight.close();
                } catch (IOException e) {
                    // TODO Auto-generated catch block
                    e.printStackTrace();
                }
            }

        } else {
            Toast.makeText(this, "不是MifareUltralightle类型", Toast.LENGTH_SHORT).show();
        }
        return null;
    }

    private String getTagId(Tag tagFromIntent) {
        //此NFC卡支持的协议
        for (String tech : tagFromIntent.getTechList()) {
            Log.e("jx", "tech = " + tech);
        }
        //读取id
        String id = bytesToHexString(tagFromIntent.getId());
        Log.e("jx", "tag.id = " + id);
        return id;
    }

    private String bytesToHexString(byte[] src) {
        StringBuilder stringBuilder = new StringBuilder("");
        if (src == null || src.length <= 0) {
            return null;
        }
        char[] buffer = new char[2];
        for (int i = 0; i < src.length; i++) {
            buffer[0] = Character.forDigit((src[i] >>> 4) & 0x0F, 16);
            buffer[1] = Character.forDigit(src[i] & 0x0F, 16);
            stringBuilder.append(buffer);
        }
        return stringBuilder.toString();
    }

    @Override
    public void showOpsList(ArrayList<TransportationRecord_Opsinfo> list) {
        opsinfos = list;
        adapter = new TransportationRecordAdapter(trsportationList, opsinfos, R.layout.item_transportrecord);
        trsportationList.setAdapter(adapter);
        emptyLayout.dismiss();
    }

    @Override
    public void execOps(String s) {

        if (s.length() > 0) {
            try {
                YXTransportationExec exec = JSON.parseObject(s, YXTransportationExec.class);
                if (exec.getBody().getHead().getRet_code().equals("0")) {
                    ViewInject.toast("转运成功");
                    loadDialog.dismiss();
                } else {
                    ViewInject.toast("转运失败");
                    loadDialog.dismiss();
                }
            } catch (Exception e) {
                YXTransportationExecFail execFail = JSON.parseObject(s, YXTransportationExecFail.class);
                ViewInject.toast(execFail.getBody().getResponse().getHead().getRet_info());
                loadDialog.dismiss();
            }
        }


//        else {
//            ViewInject.toast("转运失败");
//            loadDialog.dismiss();
//        }
    }

    @Override
    public void showRfidInfo(RfidBean rfidBean) {
        if (rfidBean != null) {
            if (rfidBean.getObject() != null) {
                this.rfidBean = rfidBean;
                transportationWorkerName.setText("护工名称:" + rfidBean.getObject().getName());
                transportationWorkerNo.setText("工号:" + rfid.substring(rfid.length() - 6, rfid.length()));
                if (opsinfo.getRequestno() != null) {
                    if (!opsinfo.getRequestno().equals("")) {
                        transportSureBtn.setEnabled(true);
                    }
                }

            } else {
                ViewInject.toast("RFID码异常,请重新识别");
            }
        }
        loadDialog.dismiss();
    }


    public void showDialog(RfidBean rfidBean) {
        builder_transportation = new Dialog_Transportation.Builder(aty);
        builder_transportation.setMessage("护工" + rfidBean.getObject().getName() + "(" + rfid.substring(rfid.length() - 6, rfid.length())
                + ") 将病人 " + PreferenceHelper.readString(aty, AppConfig.CURRENT_PATIENT_INFO, AppConfig.CURRENT_PATIENT_NAME)
                + "(" + PreferenceHelper.readString(aty, AppConfig.CURRENT_PATIENT_INFO, AppConfig.CURRENT_PATIENT_SEX) + " 住院号 "
                + PreferenceHelper.readString(aty, AppConfig.CURRENT_PATIENT_INFO, AppConfig.CURRENT_PATIENT_VISITNO) + " 床位号 "
                + PreferenceHelper.readString(aty, AppConfig.CURRENT_PATIENT_INFO, AppConfig.CURRENT_PATIENT_BEDCODE) + " )" + "进行转运");
        builder_transportation.setPositiveButton("确认",
                new DialogInterface.OnClickListener() {
                    @Override
                    public void onClick(DialogInterface dialog, int which) {
                        dialog.dismiss();
                        loadDialog.setCanceledOnTouchOutside(false);
                        loadDialog.show();
                        execOps();
                    }
                });

        builder_transportation.setNegativeButton("取消",
                new DialogInterface.OnClickListener() {
                    public void onClick(DialogInterface dialog, int which) {
                        dialog.dismiss();
                    }
                });
        builder_transportation.create().show();
    }

    private void execOps() {
        String patState = "";
        int opspatstate = Integer.valueOf(opsinfo.getOpspatstate());
        if (opspatstate < 10) {
            patState = "10";
        } else if (opspatstate >= 10 && opspatstate < 20) {
            patState = "20";
        } else if (opspatstate >= 20 && opspatstate < 80) {
            patState = "80";
        } else if (opspatstate >= 80 && opspatstate < 90) {
            patState = "90";
        }

        presenterRfid.opsExec(opsinfo.getRequestno(), patState, rfidBean.getObject().getJt_id(), rfidBean.getObject().getName(),
                PreferenceHelper.readString(aty, AppConfig.NURSE_INFO, AppConfig.NURSE_LOGID));
    }

    @Override
    public void showOpsNoticeList(ArrayList<OperNotice_OpsList> list) {
        if(list.size() > 0)
        {
            operNoticeTime.setText(list.get(0).getARRANGE_OPS_TIME());
            operNoticeVicitno.setText(list.get(0).getVISIT_NO());
            operNoticeName.setText(list.get(0).getPAT_NAME());
            operNoticeBed.setText(list.get(0).getBED_CODE());
            operNoticeDiag.setText(list.get(0).getDIAG());
            operNoticeOpsname.setText(list.get(0).getOPS_NAME());
        }
    }
}
